package org.bilinc.gz001;

import javax.swing.*;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;

public class ScrollSynchronizer implements AdjustmentListener {
    private final JScrollBar mLeftScrollVertical;
    private final JScrollBar mRightScrollVertical;
    private final JScrollBar mLeftScrollHorizontal;
    private final JScrollBar mRightScrollHorizontal;

    public ScrollSynchronizer(final JScrollPane sp1,final JScrollPane sp2) {
        mLeftScrollVertical = sp1.getVerticalScrollBar();
        mLeftScrollHorizontal = sp1.getHorizontalScrollBar();
        mRightScrollVertical = sp2.getVerticalScrollBar();
        mRightScrollHorizontal = sp2.getHorizontalScrollBar();
    }

    public void adjustmentValueChanged(AdjustmentEvent e) {
        final JScrollBar scrollBar = (JScrollBar) e.getSource();
        final int value = scrollBar.getValue();
        JScrollBar target = null;

        if (scrollBar == mLeftScrollVertical) {
            target = mRightScrollVertical;
        }
        if (scrollBar == mLeftScrollHorizontal) {
            target = mRightScrollHorizontal;
        }
        if (scrollBar == mRightScrollVertical) {
            target = mLeftScrollVertical;
        }
        if (scrollBar == mRightScrollHorizontal) {
            target = mLeftScrollHorizontal;
        }

        target.setValue(value);
    }
}